using System;
using System.Collections.Generic;
using Activa.CoolStorage;

namespace Activa.ProMesh
{
    public class CSTranslationProvider : ITranslationProvider
    {
        private readonly List<string> _languages = new List<string>();

        public CSTranslationProvider()
        {
            foreach (Language language in Language.List())
                _languages.Add(language.LanguageID);
        }

        private static readonly Dictionary<string,Dictionary<string,string>> _translationCache = new Dictionary<string, Dictionary<string, string>>(StringComparer.InvariantCultureIgnoreCase);
        
        public Dictionary<string, string> GetTranslations(string langCode, string viewName)
        {
            CSList<TranslationRecord> translations =
                TranslationRecord.List(
                    "(LanguageID IN ('*', @LanguageID)) AND (PageID IN ( '*', @PageID) OR @PageID LIKE REPLACE(PageID,'*','%'))",
                    "@LanguageID", langCode,
                    "@PageID", viewName);


            Dictionary<string, string> tags = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);

            foreach (TranslationRecord translation in translations)
            {
                tags[translation.TextID] = WikiFormatter.FormatText(translation.Text);
            }
            
            return tags;
        }

        public string GetTranslation(string langCode, string viewName, string tagName)
        {
            Dictionary<string, string> tags;

            string key = langCode + "/" + viewName;

            if (!_translationCache.TryGetValue(key, out tags))
            {
                lock (_translationCache)
                {
                    if (!_translationCache.TryGetValue(key, out tags))
                    {
                        tags = GetTranslations(langCode, viewName);

                        if (tags != null)
                            _translationCache[key] = tags;
                    }
                }
            }

            if (tags != null)
                if (tags.ContainsKey(tagName))
                    return tags[tagName];

            return null;
        }

        public string[] GetAvailableLanguages()
        {
            return _languages.ToArray();
        }
    }
}
